package com.daxidi.cn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.daxidi.cn.config.wxconfig.WxConfig;
import com.daxidi.cn.cons.ShgCons;
import com.daxidi.cn.entity.*;
import com.daxidi.cn.mapper.LogMapper;
import com.daxidi.cn.service.IClerkService;
import com.daxidi.cn.service.IMemberService;
import com.daxidi.cn.service.IShopService;
import com.daxidi.cn.service.IUserService;
import com.daxidi.cn.utils.*;
import com.daxidi.cn.vo.ClerkLoginVo;
import com.daxidi.cn.vo.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * @author JiaLin
 * create 2020-11-09
 */
@Log4j
@Api(tags = "微信登录")
@RestController
@RequestMapping(value = "/api/v1/wx")
public class WxController {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private IUserService userService;

    @Autowired
    private IMemberService memberServicel;

    @Autowired
    private IClerkService clerkService;

    @Autowired
    private IShopService shopService;

    /**
     * //https://1f2d712e4c2b.ngrok.io/wx/login
     * <p>
     * 微信登录第一步：请求获取code
     *
     * @throws Exception
     */
    /*@RequestMapping("/login")
    public void wechatLogin(HttpServletResponse response) throws Exception{
        //拼写请求获取code的地址
        StringBuilder codeUrl = new StringBuilder("https://open.weixin.qq.com/connect/qrconnect");
        codeUrl.append("?appid="+ "wx7287a60bb700fd21");
        codeUrl.append("&redirect_uri="+ "http://www.txjava.cn/loginServlet");
        codeUrl.append("&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect");
        //发送请求
        response.sendRedirect(codeUrl.toString());
    }*/

    //https://a7f4ccdf191d.ngrok.io/wx/getCode
    //http://114.215.201.161:9082//wx/api/v1/getCode
    //http://localhost:8082/wx/getCode
    @ApiOperation(value = "跳转到微信登录链接", notes = "直接在微信客户端打开")
    @GetMapping(value = "/getCode")
    public String getCode() {
        return "redirect:" + wxConfig.getCode();
    }

    //https://a7f4ccdf191d.ngrok.io/wx/callBack
    @ApiOperation(value = "微信登录回调函数", notes = "直接在微信客户端打开")
    @GetMapping(value = "/callBack")
    public void callBack(String code) throws IOException {
        String tokenUrl = wxConfig.getAccessToken(code);
        String callBackStr = HttpClientUtils.doGet(tokenUrl);

        JSONObject jsonObject = JSONObject.parseObject(callBackStr);
        System.out.println(jsonObject);
        //获取access_token，7200秒过期
        String accessToken = jsonObject.getString("access_token");
        //获取openId
        String openId = jsonObject.getString("openid");
        //获取refreshToken，30天过期
        String refreshToken = jsonObject.getString("refresh_token");

        String userInfo_str = HttpClientUtils.doGet(wxConfig.getUserInfo(accessToken, openId));
        String wxToken = accessToken;
        //redisUtils.set(wxToken, userInfo_str, 7200);
        //JSONObject.parseObject(userInfo_str, UsersVo.class);
        System.out.println(userInfo_str);
    }

    @ApiOperation(value = "会员微信登录返回", notes = "返回openId，成功返回member对象，失败返回401")
    @GetMapping(value = "/wxLoginBack")
    public ReturnResult wxLoginBack(@RequestParam String appId, @RequestParam String code) throws IOException {
        Long timestamp1 = System.currentTimeMillis();
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String tokenUrl = wxConfig.getOpenId(appId, code);
        String callBackStr = HttpClientUtils.doGet(tokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(callBackStr);
        //获取openId
        String openId = jsonObject.getString("openid");
        //user表中有记录
        if (null != userService.selectMemberIdByOpenId(openId)) {
            Long memberId = userService.selectMemberIdByOpenId(openId);
            Member member = memberServicel.selectMemberByMemberId(memberId);
            if (member.getEnable() == 0) {
                HashMap<String, Object> hashMap = new HashMap();
                hashMap.put("msg", "用户已下线，请联系管理员！");
                hashMap.put("openId", openId);
                return ReturnResultUtils.returnFailMsgData(916, hashMap);
            }
            UserLoginVo userLoginVo = new UserLoginVo();
            userLoginVo.setOpenId(openId);
            userLoginVo.setMemberId(memberId);
            userLoginVo.setUserName(member.getName());
            userLoginVo.setCode(member.getCode());
            User user = userService.selectUserByOpenId(openId);
            userLoginVo.setUserId(user.getId());
            userLoginVo.setNickName(user.getNickname());
            userLoginVo.setAvatarUrl(user.getAvatarurl());
            userLoginVo.setMobile(user.getMobile());

            HashMap<String, Object> map = new HashMap<>();
            map.put("userLoginVo", userLoginVo);
            String tokenName = null;
            if (StringUtils.isEmpty(member.getName())) {
                tokenName = userLoginVo.getNickName();
            } else {
                tokenName = member.getName();
            }
            String token = JWTUtils.generate(tokenName);
            //redisUtils.set(ShgCons.TOKEN_MEMBER + token, JSON.toJSONString(userLoginVo), 18000);
            map.put("token", token);
            log.info("member login :" + map);
            //添加日志
            Log log = new Log();
            log.setLogAt(new Date(timestamp1));
            String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
            log.setLogIp(ipAddrByRequest);
            log.setLogContent("会员登录");
            log.setLogTime(System.currentTimeMillis() - timestamp1);
            log.setLogType("SELECT");
            log.setUsername(StringUtils.isEmpty(member.getName()) ? "未添加的用户名" : member.getName());
            logMapper.insert(log);
            return ReturnResultUtils.returnSuccess(map);
        } else {
            return ReturnResultUtils.returnFailMsg(401, openId);
        }
    }

    @ApiOperation(value = "店员微信登录返回", notes = "返回openId，成功返回clerk对象，失败返回401")
    @GetMapping(value = "/wxLoginBackClerk")
    public ReturnResult wxLoginBackClerk(@RequestParam String appId, @RequestParam String code) throws IOException {
        Long timestamp1 = System.currentTimeMillis();
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String tokenUrl = wxConfig.getClerkOpenId(appId, code);
        String callBackStr = HttpClientUtils.doGet(tokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(callBackStr);
        //获取openId
        String openId = jsonObject.getString("openid");
        //user表中有记录
        if (null != userService.selectClerkIdByOpenId(openId)) {
            //根据openId获取店员Id
            Long clerkId = userService.selectClerkIdByOpenId(openId);
            //根据店员id获取店员信息
            Clerk clerk = clerkService.selectClerkById(clerkId);
            if (clerk.getEnable() == false) {
                return ReturnResultUtils.returnFailMsg(845, "该店员已注销，请联系管理员！");
            }
            //获取微信登录的信息
            User user = userService.selectUserByOpenId(openId);
            ClerkLoginVo clerkLoginVo = new ClerkLoginVo();
            //店员名字
            clerkLoginVo.setClerkName(clerk.getName());
            //店员手机
            clerkLoginVo.setClerkMobile(clerk.getMoblie());
            //店员头像
            clerkLoginVo.setAvatarUrl(user.getAvatarurl());
            //店员Id
            clerkLoginVo.setClerkId(clerkId);
            //店铺Id
            clerkLoginVo.setShopId(clerk.getShopId());
            //获取店铺信息
            Shop shop = shopService.selectShop(clerk.getShopId());
            //店铺名称
            clerkLoginVo.setShopName(shop.getName());
            //经度
            clerkLoginVo.setLogitiude(shop.getLogitiude());
            //纬度
            clerkLoginVo.setLagitude(shop.getLagitude());
            //店铺位置
            clerkLoginVo.setAddress(shop.getAddress());
            //角色
            clerkLoginVo.setRole(clerk.getRole());

            HashMap<String, Object> map = new HashMap<>();
            map.put("clerkLoginVo", clerkLoginVo);
            String tokenName = null;
            if (StringUtils.isEmpty(clerk.getName())) {
                tokenName = clerkLoginVo.getClerkName();
            } else {
                tokenName = clerk.getName();
            }
            String token = JWTUtils.generate(tokenName);
            //redisUtils.set(ShgCons.TOKEN_CLERK + token, JSON.toJSONString(clerkLoginVo), 18000);
            map.put("token", token);
            map.put("openId", openId);
            map.put("discount", shop.getDiscount());
            log.info("clerk login :" + map);
            //添加日志记录
            Log log = new Log();
            log.setLogAt(new Date(timestamp1));
            String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
            log.setLogIp(ipAddrByRequest);
            log.setLogContent("店员登录");
            log.setLogTime(System.currentTimeMillis() - timestamp1);
            log.setLogType("SELECT");
            log.setUsername(StringUtils.isEmpty(clerk.getName()) ? "未添加的用户名" : clerk.getName());
            logMapper.insert(log);
            return ReturnResultUtils.returnSuccess(map);
        } else {
            return ReturnResultUtils.returnFailMsg(401, openId);
        }
    }

}
